package com.minyifang.wcspf.work.ui.home.activities;

import android.Manifest;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.adapter.GeneralFragmentPagerAdapter;
import com.minyifang.wcspf.common.base.BaseMvpActivity;
import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.SPUtils;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.work.event.RefreshEvent;
import com.minyifang.wcspf.work.model.HttpRespond;
import com.minyifang.wcspf.work.service.DownLoadHelper;
import com.minyifang.wcspf.work.ui.Global;
import com.minyifang.wcspf.work.ui.home.fragments.HomePage1Fragment;
import com.minyifang.wcspf.work.ui.home.fragments.HomePage2Fragment;
import com.minyifang.wcspf.work.ui.home.fragments.HomePage3Fragment;
import com.minyifang.wcspf.work.ui.home.fragments.HomePage4Fragment;
import com.minyifang.wcspf.work.ui.home.model.ShoppingCarBean;
import com.minyifang.wcspf.work.ui.home.model.SplashBean;
import com.minyifang.wcspf.work.ui.home.presenter.MainPresenter;
import com.minyifang.wcspf.work.ui.home.view.MainView;
import com.minyifang.wcspf.work.ui.user.model.VersionBean;
import com.minyifang.wcspf.work.ui.widgets.DownloadPackageDialog;
import com.yanzhenjie.permission.AndPermission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 主页面
 */
public class MainActivity extends BaseMvpActivity<MainView, MainPresenter> implements MainView {

    public static final String BROADCAST_CHECK_CLASS = "checkclass";
    public static final String BROADCAST_CHECK_CART = "checkcart";
    @BindView(R.id.tv_num)
    TextView tv_num;

    @BindView(R.id.vp_fragment)
    ViewPager mVpFragment;
    @BindView(R.id.rg_tab)
    RadioGroup mRgTab;
    private List<Fragment> mFragments = new ArrayList<>();
    private MyReceiver mReceiver;
    private boolean mShowCarTips;
    private HomePage2Fragment mHomePage2Fragment;

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
//        overridePendingTransition(0, 0);
        mReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter(BROADCAST_CHECK_CLASS);
        filter.addAction(BROADCAST_CHECK_CART);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
        requestTranslucentStatusBar(Color.TRANSPARENT, true);
        initTabBar();
    }

    /**
     * 初始化tab 栏
     */
    private void initTabBar() {
        mFragments.add(new HomePage1Fragment());
        mHomePage2Fragment = new HomePage2Fragment();
        mFragments.add(mHomePage2Fragment);
        mFragments.add(new HomePage3Fragment());
        mFragments.add(new HomePage4Fragment());
        mVpFragment.setAdapter(new GeneralFragmentPagerAdapter(getSupportFragmentManager(), mFragments));
        mRgTab.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_0:
                    mVpFragment.setCurrentItem(0, false);
                    requestTranslucentStatusBar(Color.TRANSPARENT, false);
                    tv_num.setVisibility(mShowCarTips ? View.GONE : View.VISIBLE);
                    break;
                case R.id.rb_1:
                    mVpFragment.setCurrentItem(1, false);
                    mHomePage2Fragment.initiativeRefreshGoodsList();
                    tv_num.setVisibility(mShowCarTips ? View.GONE : View.VISIBLE);
                    break;
                case R.id.rb_2:
                    mVpFragment.setCurrentItem(2, false);
                    tv_num.setVisibility(View.GONE);
                    break;
                case R.id.rb_3:
                    mVpFragment.setCurrentItem(3, false);
                    tv_num.setVisibility(mShowCarTips ? View.GONE : View.VISIBLE);
                    break;
            }
        });
        mVpFragment.setOffscreenPageLimit(4);
        //默认选中第一个页面
        mRgTab.check(R.id.rb_0);
    }

    @Override
    protected void initData() {
        AndPermission.with(this).permission(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(permissions -> {
                    downLoadSplashContent();
                    checkVersion();
                }).start();
    }

    protected void installApk(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
            Uri apkUri = FileProvider.getUriForFile(this, "com.minyifang.wcspf.fileprovider", file);  //包名.fileprovider
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        try {
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "未找到安装程序", Toast.LENGTH_SHORT).show();
        }
    }

    private static final long DELAY_TIME = 1500;
    long lastPressBackKeyTime = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
            super.onBackPressed();
        } else {
            lastPressBackKeyTime = System.currentTimeMillis();
            ToastHelper.getInstance(this).showWarn("再按一次退出应用");
        }
    }

    public void checkMoudle(int position) {
        switch (position) {
            case 0:
                mRgTab.check(R.id.rb_0);
                tv_num.setVisibility(mShowCarTips ? View.GONE : View.VISIBLE);
                break;
            case 1:
                mRgTab.check(R.id.rb_1);
                tv_num.setVisibility(mShowCarTips ? View.GONE : View.VISIBLE);
                break;
            case 2:
                mRgTab.check(R.id.rb_2);
                tv_num.setVisibility(mShowCarTips ? View.GONE : View.GONE);
                break;
            case 3:
                mRgTab.check(R.id.rb_3);
                tv_num.setVisibility(mShowCarTips ? View.GONE : View.VISIBLE);
                break;
        }
    }

    public void checkClass(String classId) {
        checkMoudle(1);
        ((HomePage2Fragment) mFragments.get(1)).checkClassByClassId(classId);
    }

    public void checkSubClass(String classId, String subClassId) {
        checkMoudle(1);
        ((HomePage2Fragment) mFragments.get(1)).checkClassBySubClassId(classId, subClassId);
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
    }

    /**
     * 启动服务下载启动页内容
     */
    private void downLoadSplashContent() {
        mPresenter.getSplashContent();
    }

    private void checkVersion() {
        mPresenter.checkVersion();
    }

    @Override
    public void showSplashContent(HttpRespond<SplashBean> respond) {
        if (respond.result == 1) {
            SplashBean bean = respond.data;
            int second = bean.getSecond();
            SPUtils.put(this, "splash_second", second);
            String url = bean.getUrl().substring(bean.getUrl().lastIndexOf("/") + 1);
            String localUrl = (String) SPUtils.get(this, "splash_path", "");
            if (url.equals(localUrl.substring(localUrl.lastIndexOf("/") + 1))) {
                return;
            }
            LogUtil.e("启动页类型: " + bean.getType() + ",地址:" + bean.getUrl());
            if (bean.getType() == 1) {
                DownLoadHelper.downLoad(this, bean.getUrl(), false, bean.getType());
            }
        } else
            ToastHelper.getInstance(this).showError(respond.message);
    }

    File mApkFile;

    @Override
    public void showVersionInfo(HttpRespond<VersionBean> respond) {
        if (respond.result == 1) {
            VersionBean data = respond.data;
            //1强制更新0,不强制更新,2不更新

            if (data.getIsForced() == 2 || respond.data == null) {
                return;
            }
//            Dialog dialog = new UpdateDialog.Builder(this)
//                    .setTitle("发现新版本" + data.getVersion())
//                    .setContent(data.getUpdateContent())
//                    .setSingleBtn(data.isMustUpdate())
//                    .setListener(new UpdateDialog.OnButtonClickListener() {
//                        @Override
//                        public void onConfirm(Dialog dialog) {
//                            if (!data.isMustUpdate())
//                                dialog.dismiss();
//                            openSystemBrowser(data.getURL());
//                        }
//
//                        @Override
//                        public void onCancel(Dialog dialog) {
//                            dialog.dismiss();
//                        }
//                    }).build();
//            dialog.setCancelable(!data.isMustUpdate());
//            dialog.show();

            new DownloadPackageDialog.Builder(this)
                    .setTitle("发现新版本" + data.getVersion())
                    .setContent(data.getUpdateContent())
                    .setUrl(data.getURL())
                    .setListener(new DownloadPackageDialog.Builder.Listener() {
                        @Override
                        public void urlMayNotAApkFile(Dialog dialog, String url) {
                            if (!data.isMustUpdate())
                                dialog.dismiss();
                            ToastHelper.getInstance(MainActivity.this).showWarn("下载地址可能不是文件，将调用其他应用打开");
                            openSystemBrowser(url);
                        }

                        @Override
                        public void onDownloadComplete(Dialog dialog, File file) {
                            mApkFile = file;
                            if (!data.isMustUpdate())
                                dialog.dismiss();
                            checkIsAndroidO();
                        }
                    }).show(!data.isMustUpdate());
        }
        //退出App
        if (respond.result == -2)
            Global.exitApp(this, respond.message);

    }

    public void checkIsAndroidO() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasPermission = getPackageManager().canRequestPackageInstalls();
            if (hasPermission) {
                installApk(mApkFile);
            } else {
                //请求安装未知应用来源的权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 10010);
            }
        } else {
            installApk(mApkFile);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 10010:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    installApk(mApkFile);
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    ToastHelper.getInstance(MainActivity.this).showWarn("请授与安装权限");
                    startActivityForResult(intent, 10012);
                }
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10012:
                checkIsAndroidO();
                break;
            default:
                break;
        }
    }

    /**
     * 打开系统浏览器
     *
     * @param url
     */
    private void openSystemBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        try {
            intent.setData(Uri.parse(url));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            ToastHelper.getInstance(this).showWarn("未找到合适的应用");
        }
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
        DownLoadHelper.unregisterReceiver();
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BROADCAST_CHECK_CLASS:
                    checkMoudle(1);
                    break;
                case BROADCAST_CHECK_CART:
                    checkMoudle(2);
                    break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getCarNum();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCarNum(RefreshEvent event) {
        mPresenter.getCarNum();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void showCarNum(HttpRespond<ShoppingCarBean> response) {
        if (response.result == 1) {
            ShoppingCarBean bean = response.data;
            tv_num.setVisibility(bean.getNum() == 0 ? View.GONE : View.VISIBLE);
            mShowCarTips = bean.getNum() == 0;
            tv_num.setText(String.format("共%d种，%s元", bean.getNum(), bean.getPrice()));
        }
    }
}